package org.yxjme.ijkplayerlibrary.android;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;


public class TouchListener  implements View.OnTouchListener{

    private boolean isLeft ;
    private boolean isRight ;
    private Context context ;

    private float downX ;
    private float downY ;

    private FrameLayout contentView;
    private int viewWidth ;
    private int viewHeight ;
    private AudioManager audioManager ;

    private int minVolume ;
    private int maxVolume ;
    private int currentVolume;
    private ChangeVolumeView changeVolumeView;

    private ChangeLightView changeLightView;
    private float currentBrightness;


    public TouchListener(Context context, FrameLayout contentView, ChangeLightView changeLightView, ChangeVolumeView changeVolumeView){
        this.context=context;
        this.contentView=contentView;
        this.changeVolumeView=changeVolumeView;
        this.changeLightView=changeLightView;


        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) ;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
            minVolume = audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC) ;
        }
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) ;

        Log.v("[TouchListener]->","maxVolume = "+maxVolume+",currentVolume = "+currentVolume+",minVolume="+minVolume);
    }



    @Override
    public boolean onTouch(View v, MotionEvent event) {

        viewWidth = contentView.getWidth();
        viewHeight = contentView.getHeight();

        Log.v("[TouchListener]->","ACTION_DOWN = "+viewWidth);

        switch (event.getAction()){

            case MotionEvent.ACTION_DOWN:

                isLeft = false ;
                isRight = false ;

                downX = event.getX() ;
                downY = event.getY() ;

                if (viewWidth / 2 > downX){
                    CheckPermission();
                }else {
                    isRight = true ;
                    currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) ;
                }
                break;

            case MotionEvent.ACTION_MOVE:
                /*当前滑动的高度*/
                float moveX = event.getX() - downX ;
                float moveY = event.getY() - downY ;

                float radio = (float) (moveY *1.0 / viewHeight);
                if (radio>1){
                    radio = 1 ;
                }

                if (radio<-1){
                    radio = -1 ;
                }

                /*左边触摸改变亮度*/
                if (isLeft){
                    if (Math.abs(moveY)>ViewConfiguration.getTouchSlop()){
                        changeLight(radio);
                    }
                }

                /*右边触摸改变音量*/
                if (isRight){
                    if (Math.abs(moveY)>ViewConfiguration.getTouchSlop()){
                        changeVolume(radio);
                    }
                }

                Log.v("[TouchListener]->","radio = "+radio);
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                Log.v("[TouchListener]->","ACTION_UP");
                changeVolumeView.setVisibility(View.GONE);
                changeLightView.setVisibility(View.GONE);
                break;
        }
        return false;
    }



    /**
     *
     *
     *
     */
    private void CheckPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(context)) {
            Toast.makeText(context,"请在该设置页面勾选，才可以使用路况提醒功能",Toast.LENGTH_LONG).show();
            Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }else {
            isLeft = true ;
            currentBrightness = systemBrightness();
        }
    }



    /**
     * 改变亮度
     *
     * @param radio
     */
    private void changeLight(float radio) {
        Log.v("[TouchListener]->","radio = "+radio+",currentBrightness="+currentBrightness);
        changeLightView.setVisibility(View.VISIBLE);
        float resultBrightness = (float) ((currentBrightness + -radio * 255) * 1.0 /255);
        changeLightView.setProgressLight((int) (resultBrightness * 100));
        if (resultBrightness>1){
            resultBrightness = 1 ;
        }
        if (resultBrightness<0){
            resultBrightness = 0 ;
        }

        Window window = getAppCompatActivity(context).getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = resultBrightness;
        window.setAttributes(lp);
        Log.v("[TouchListener]->","resultBrightness = "+resultBrightness);
        Settings.System.putInt(context.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS, (int) (currentBrightness + -radio * 255));
    }



    /**
     * 得到AppCompactActivity
     *
     * @param context 上下文
     * @return
     */
    public static AppCompatActivity getAppCompatActivity(Context context) {
        if (context == null) {
            return null;
        }
        if (context instanceof AppCompatActivity) {
            return (AppCompatActivity) context;
        } else if (context instanceof ContextThemeWrapper) {
            return getAppCompatActivity(((ContextThemeWrapper) context).getBaseContext());
        }
        return null;
    }



    /**
     *  获取系统亮度
     */
    public float systemBrightness(){
        float systemBrightness = 0f;
        try {
            systemBrightness = Settings.System.getFloat(context.getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS) ;
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }



    /**
     * 改变音量
     *
     * @param radio
     */
    private void changeVolume(float radio) {
        changeVolumeView.setVisibility(View.VISIBLE);
        /*获取当变化的音量*/
        int changeVolume = (int) (-radio * maxVolume);
        /*得到变化后的当前音量*/
        int resultVolume=currentVolume+changeVolume ;
        /*最大边际值*/
        if (resultVolume>maxVolume){
            resultVolume = maxVolume ;
        }
        /*最小边际值*/
        if (resultVolume<minVolume){
            resultVolume = minVolume ;
        }
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, resultVolume, AudioManager.FLAG_PLAY_SOUND);
        int  p  = (int) ((resultVolume*1.0 / maxVolume) * 100);
        changeVolumeView.setProgressVolume(p);
    }
}
